package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.Destination;
import cn.wolfcode.wolf2w.domain.Region;
import cn.wolfcode.wolf2w.query.RegionQuery;
import cn.wolfcode.wolf2w.repository.DestinationMongoRepository;
import cn.wolfcode.wolf2w.repository.RegionMongoRepository;
import cn.wolfcode.wolf2w.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class RegionServiceImpl implements IRegionService {
    
    @Autowired
    private RegionMongoRepository regionMongoRepository;

    @Autowired
    private DestinationMongoRepository destinationMongoRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Region region) {
        region.setId(null);
        regionMongoRepository.save(region);
    }

    @Override
    public void update(Region region) {
        regionMongoRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionMongoRepository.deleteById(id);
    }

    @Override
    public Region get(String id) {
        return regionMongoRepository.findById(id).orElse(null);
    }

    @Override
    public List<Region> list() {
        return regionMongoRepository.findAll();
    }

    @Override
    public Page<Region> query(RegionQuery qo) {
        // 创建查询对象
        Query query = new Query();

        // 查询总条数
        long count = template.count(query, Region.class);
        // 调用PageRequest 方法进行分页
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        // 给查询对象设置条件
        query.with(pageable);
        // 从mongodb 中查询符合条件的数据
        List<Region> regions = template.find(query, Region.class);
        // 返回当前页数据,分页和总长度
        return new PageImpl<>(regions , pageable , count);
    }

    @Override
    public void saveOrUpdate(Region region) {
        if (StringUtils.hasLength(region.getId())){
            this.update(region);
        }else {
            this.save(region);
        }
    }

    @Override
    public void getByIsHot(int hot, String id) {
        // 查询
        Region region = this.get(id);
        // 设置
        region.setIshot(hot);
        // 修改
        this.update(region);
    }

    @Override
    public List<Region> queryHot() {
        // 通过jpa 格式查询热门的城市  Region.STATE_HOT 热门城市参数
        return regionMongoRepository.findByIshotOrderBySequence(Region.STATE_HOT);

    }


}
